package com.pks.datacenter.service.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pks.datacenter.config.RedisKeyConfig;
import com.pks.datacenter.entity.api.ApiPerm;
import com.pks.datacenter.handler.RedisHandler;
import com.pks.datacenter.mapper.api.ApiPermMapper;
import com.pks.util.SUtilQbuilder;
import com.pks.web.mybatis.service.BasicServiceImpl;

@Component("apiPermService")
public class ApiPermServiceImpl extends BasicServiceImpl<ApiPerm, Long, ApiPermMapper> implements ApiPermService {

	@Autowired
	private ApiPermMapper apiPermMapper;
	@Autowired
	private RedisHandler redisHandler;

	@Override
	protected ApiPermMapper getMapper() {
		return apiPermMapper;
	}

	@Override
	public void insertPerms(Long apiUserId, List<Long> apiIds) {
		Map<String, Object> qbuilder = new HashMap<String, Object>();
        qbuilder.put("apiUserId", apiUserId);
        qbuilder.put("apiIds", apiIds);
        List<ApiPerm> apiPermList = apiPermMapper.find(qbuilder, null, null, null);
        List<Long> hasPermApiIds = new ArrayList<Long>();
        for (ApiPerm apiPerm : apiPermList) {
        	hasPermApiIds.add(apiPerm.getApiId());
		}
        List<ApiPerm> inserts = new ArrayList<ApiPerm>();
        for (Long apiId : apiIds) {
			if (!hasPermApiIds.contains(apiId)) {
				ApiPerm perm = new ApiPerm();
				perm.insertBefore();
				perm.setApiUserId(apiUserId);
				perm.setApiId(apiId);
				inserts.add(perm);
			}
		}
        if (inserts.size() > 0) {
        	apiPermMapper.inserts(inserts);
        }
        // 权限变动 清空redis 缓存 待使用时重新获取最新数据
        redisHandler.del(RedisKeyConfig.KEY_LIST_APIUSER_PERM_PREFIX + apiUserId);
	}

	@Override
	public void removePerms(Long apiUserId, List<Long> apiIds) {
		apiPermMapper.removePerms(apiUserId,apiIds);
		// 权限变动 清空redis 缓存 待使用时重新获取最新数据
		redisHandler.del(RedisKeyConfig.KEY_LIST_APIUSER_PERM_PREFIX + apiUserId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public ApiPerm findApiPerm(Long apiUserId, Long apiId) {
		ApiPerm result = null;
		if (apiUserId != null && apiId != null) {
			List<ApiPerm> list = new ArrayList<ApiPerm>();
			Object obj = redisHandler.get(RedisKeyConfig.KEY_LIST_APIUSER_PERM_PREFIX + apiUserId) ; 
			if (obj != null) {
				list = (List<ApiPerm>) obj;
			} else {
				list = apiPermMapper.find(SUtilQbuilder.initQbuilder("apiUserId", apiUserId), null, null, null);
				redisHandler.set(RedisKeyConfig.KEY_LIST_APIUSER_PERM_PREFIX + apiUserId, list , RedisKeyConfig.CACHE_TIME );
			}
			for (ApiPerm apiPerm : list) {
				if (apiPerm.getApiId().equals(apiId)) {
					result = apiPerm;
					break;
				}
 			}
		}
		return result;
	}
	
}
